# -*- coding: utf-8 -*-
"""
@Time: 12/9/2018 4:12 PM
@Author: hejing
@Email: 2010jing@gmail.com
"""
from multiprocessing import Pool
import os, time, random
import pymysql
import time, requests
from concurrent.futures import ProcessPoolExecutor


def long_time_task(data):
	print('Run task %s (%s)...' % (os.getpid(), os.getpid()))
	start = time.time()
	data_handler(data)
	# with ProcessPoolExecutor() as excute:
	# 	excute.map(data_handler, data)
	end = time.time()
	print('Task %s runs %0.2f seconds.' % (os.getpid(), (end - start)))


def data_handler(data):
	conn = pymysql.connect(host='120.79.254.19', user='root', password='zsdx2016', database='hj', charset='utf8')
	cursor = conn.cursor()
	print(data[0])
	print(data[1])
	for i in range(data[0], data[1]):
		sql = 'insert into testsql(name,email,password) values(%s,concat(%s,"@uic.edu.hk"),%s);'
		res = cursor.execute(sql, [i, "root", i])
		conn.commit()
	cursor.close()
	conn.close()




if __name__ == '__main__':
	start = time.time()
	# datas = [(0, 2500000), (2500000, 5000000), (5000000, 7500000), (7500000, 10000000)]
	datas = [(0, 250000), (250000, 500000), (500000, 750000), (750000, 1000000)]

	print('Parent process %s.' % os.getpid())
	p = Pool(4)
	p.map(long_time_task, [i for i in datas])
	print('All subprocesses done.')
	end = time.time()
	print('Task %s runs %0.2f seconds.' % (os.getpid(), (end - start)))
